//
//  DSViewController.swift
//  MM
//
//  Created by liujianlong on 2022/8/1.
//

import UIKit
import SnapKit
import TCCKit
class DSViewController : UIViewController {
    var settingBtn : UIButton!
    var saveBtn : UIButton!
    var addBtn : UIButton!
    var lockBtn : UIButton!
    ///指定键盘顶部距离第一响应的便宜距离
    var offsetH_KeyboardHidden = 0.0
    var connectStatus : BLEStatus = .normal
    var bytes = [UInt8]()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.bgHexColor = "#C0C0C0"
        initNavigationBar()
        setupNaviBarColor("#161718".color(), "#000000".color())
        addTap()
        addNotify()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .darkContent
    }
    
    func initUI(){}
    func initData(){}
    
    deinit{
        NotifyTool.remove(self)
    }
    
    func initNavigationBar(){
        let item1 = initBarButton("setting", 200, &settingBtn)
        let item2 = initBarButton("save", 201, &saveBtn)
        let item3 = initBarButton("add", 202, &addBtn)
        let item4 = initBarButton("lock", 203, &lockBtn)
        
        let longPress = UILongPressGestureRecognizer()
        longPress.minimumPressDuration = 6
        longPress.addTarget(self, action: #selector(actionForLongPress))
        item1.customView?.addGestureRecognizer(longPress)
        func initBarButton(_ img:String, _ tag:Int, _ sender:inout UIButton?)->UIBarButtonItem{
            var btn = sender ?? UIButton(type: .custom)
            btn = UIButton(type: .custom)
            //            btn.backgroundColor = .green
            btn.imageView?.contentMode = .scaleAspectFit
            //btn.imageEdgeInsets = .zero
            btn.contentHorizontalAlignment = .fill
            btn.contentVerticalAlignment = .fill
            btn.tag = tag
            btn.frame = CGRect(x: 0, y: kUIStatusBarHeight + 5, width: 40, height: 30)
            btn.addTarget(self, action: #selector(backBtnNavBtn), for: .touchUpInside)
            btn.setImage(UIImage(named:img), for: .normal)
            sender = btn
            return UIBarButtonItem(customView: btn)
        }
        
        navigationItem.leftBarButtonItems = [item1,item2]
        navigationItem.rightBarButtonItems = [item4,item3]
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.black, .font:font(18)]
    }
    
    func setupNaviBarColor(_ bgcolor:UIColor, _ titleColor:UIColor){
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.backgroundColor = bgcolor
            //appearance.backgroundImage = UIImage.withColor(bgcolor)
            appearance.backgroundImage = UIImage(named: "bg_nav")
            appearance.shadowColor = .clear///下划线颜色
            appearance.titleTextAttributes = [.foregroundColor:titleColor,.font:UIFont.systemFont(ofSize: 19)]
            navigationController?.navigationBar.setBackgroundImage(UIImage.withColor(bgcolor), for: .default)
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
            navigationController?.navigationBar.isTranslucent = false
        }else{
            navigationController?.navigationBar.shadowImage = UIImage()
            navigationController?.navigationBar.barTintColor = bgcolor
            navigationController?.navigationBar.titleTextAttributes = [.foregroundColor:titleColor]
            navigationController?.navigationBar.tintColor = titleColor
            navigationController?.navigationBar.isTranslucent = false
            navigationController?.navigationBar.setBackgroundImage(UIImage(named: "bg_nav"), for: .default)
        }
    }
    
    ///添加点击手势
    func addTap(){
        let tap = UITapGestureRecognizer(target: self, action: #selector(actionForTap))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    /// 点击空白处隐藏键盘
    @objc func actionForTap(sender:UITapGestureRecognizer){
        // 获取点击位置的视图
        let location = sender.location(in: view)
        let tappedView = view.hitTest(location, with: nil)
        
        // 判断点击的视图是否为 UIButton 类型
        if !(tappedView is UIButton) {
            view.endEditing(true)
        }
    }
    
    @objc func actionForLongPress(sender:UILongPressGestureRecognizer){
        if sender.state == .began{
            present(NoiseController(), animated: false)
            let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
            feedbackGenerator.impactOccurred()
        }
    }
    
    @objc func backBtnNavBtn(sender:UIButton){
        print("=====点击导航按钮 tag =\(sender.tag)")
        switch sender{
        case settingBtn:
            present(SearchController(), animated: false)
        case saveBtn:
            present(SaveController(), animated: false)
        case addBtn:
            let vc = AlertController()
            vc.msg.text = "Please confirm to upload current device DSP data?\nIt takes one minute to uplaod"
            vc.style = .normal
            vc.rightBlock = {_ in
                DSBleDataTool.share.dataCount = 0
                CLHUD(type: .loading,time: 100, callBack: nil)
                _ = BLEData.deviceData.write()
            }
            present(vc, animated: false)
        case lockBtn:///人形锁
            guard let pwd = UserDefaults.standard.value(forKey: FunctionLockPassword) as? String, pwd.count > 0 else {return}
            
            let vc = AlertController()
            vc.msg.text = "Please enter your password"
            vc.tips.text = "Change your password"
            vc.style = .input
            present(vc, animated: false)
            
            vc.rightBlock = {[weak self] text in
                if text != pwd{
                    CLHUD("The password is incorrect",type: .error,time:1.5, callBack: nil)
                    return
                }
                APP.pwd = text
                NotifyTool.post(updateChannelManager)
                NotifyTool.post(updateTabColor)
            }
            vc.tipsBlock = {[weak self] in
                changePWD(pwd)
            }
            
            func changePWD(_ pwd:String){
                let pvc = PWDController()
                pvc.type = .reset
                present(pvc, animated: false)
                pvc.block = {[weak self] (text1,text2,text3) in
                    if text1 != pwd{
                        CLHUD("The password is incorrect",type: .error,time:1.5, callBack: nil)
                        return false
                    }
                    UserDefaults.standard.setValue(text2, forKey: FunctionLockPassword)
                    APP.pwd = text2
                    NotifyTool.post(updateChannelManager)
                    NotifyTool.post(updateTabColor)
                    return true
                }
            }
        default:
            break
        }
    }
    
    var tableViewStyle : UITableView.Style = .plain
    @objc lazy var tableView:UITableView =
    {
        let view = UITableView(frame:.zero, style:tableViewStyle)
        view.separatorStyle = .none
        view.separatorInset = UIEdgeInsets(top: 0, left: kUIScreenWidth, bottom: 0, right: 0)
        view.bounces = false
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.tableHeaderView = UIView(frame:CGRect(x: 0, y: 0, width: 0, height: 0.01))
        view.tableFooterView = UIView(frame:CGRect(x: 0, y: 0, width: 0, height: 0.01))
        view.backgroundColor = "#C0C0C0".color()
        if #available(iOS 11.0, *) {
            view.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        if #available(iOS 15.0, *) {
            view.sectionHeaderTopPadding = 0
        } else { }
        self.view.addSubview(view)
        return view
    }()
    
    var autoAddCollectionView : Bool = true
    var flowLayout = UICollectionViewFlowLayout()
    @objc lazy var collectionView: UICollectionView =
    {
        let view = UICollectionView(frame:.zero, collectionViewLayout:flowLayout)
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        view.backgroundColor = "#161718".color()
        if #available(iOS 11.0, *) {
            view.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        if autoAddCollectionView{
            self.view.addSubview(view)
        }
        return view
    }()
}


//MARK: - 通知
extension DSViewController{
    @objc func addNotify(){
        NotifyTool.add(self, #selector(methodKeyboardShow),UIResponder.keyboardWillChangeFrameNotification.rawValue)
        NotifyTool.add(self, #selector(methodKeyboardHidden), UIResponder.keyboardWillHideNotification.rawValue)
        NotifyTool.add(self, #selector(methodConnectStatus), BLEStatusUpdateNotifyName)
    }
    
    @objc func removeNotify(){
        NotifyTool.remove(self)
    }
    
    @objc func methodKeyboardShow(_ notify:Notification){
        let userinfo = notify.userInfo
        let value = userinfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
        let time = (userinfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber) .doubleValue
        let keyboard_H = value.cgRectValue.size.height
        var maxY : CGFloat = 0
        
        let view = firstResponder(self.view)
        if view == nil{
            return
        }
        let rect = view!.convert(view!.bounds, to: UIApplication.shared.delegate!.window!)
        maxY = rect.maxY
        
        let map = kUIScreenHeight - maxY - keyboard_H - offsetH_KeyboardHidden
        if map < 0 {
            UIView.animate(withDuration: time) {
                self.view.transform = CGAffineTransform(translationX: 0, y: map)
            }
        }
    }
    
    @objc func methodKeyboardHidden(_ notify:Notification){
        let time = (notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber) .doubleValue
        UIView.animate(withDuration: time) {
            self.view.transform = CGAffineTransform.identity
        }
    }
    
    @objc func methodConnectStatus(){
        connectStatus = BLE.status
        // if self.className != self.currentVC().className {return}
        switch BLE.status{
        case .connectedSucces:
            if self.currentVC().className == "QCAlertPopViewController"{
                return
            }
        case .didDiscoverCharacteristics:
            break
        case .disconnect:
            if BLE.connectedPeripherals.count > 0 {return}
            break
        default:
            break
        }
    }
}
